// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.dcel.parser;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.dustedpixels.dcel.Instance;
import com.dustedpixels.dcel.Unit;
import com.dustedpixels.dcel.Unit.Pin;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
abstract class BaseInstance implements Instance {
  final Unit unit;
  final Map<String, int[]> pinData;
  final Set<String> pinNames;

  public BaseInstance(Unit unit) {
    this.unit = unit;
    this.pinData = new HashMap<String, int[]>();
    this.pinNames = new HashSet<String>();
    for (Pin pin : unit.getPins()) {
      pinNames.add(pin.getName());
    }
  }
  
  public Unit getUnit() {
    return unit;
  }

  public void setPinData(String pinName, int[] data) {
    if (!pinNames.contains(pinName)) {
      throw new IllegalArgumentException("No such pin: " + data);
    }
    
    pinData.put(pinName, data);
  }

  public void run(int cycles) {
    for (Map.Entry<String, int[]> entry : pinData.entrySet()) {
      if (entry.getValue().length != cycles) {
        throw new IllegalStateException("Invalid pin data size: " + entry.getKey());
      }
    }
    
    if (cycles > 0) {
      doRun(cycles);
    }
  }

  abstract void doRun(int cycles);
}
